package jaux.tank.utils;

import java.io.ByteArrayOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.io.InputStream;
import java.nio.charset.StandardCharsets;
import java.security.InvalidAlgorithmParameterException;
import java.security.InvalidKeyException;
import java.security.MessageDigest;
import java.security.NoSuchAlgorithmException;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;

import javax.crypto.BadPaddingException;
import javax.crypto.Cipher;
import javax.crypto.IllegalBlockSizeException;
import javax.crypto.NoSuchPaddingException;
import javax.crypto.SecretKey;
import javax.crypto.spec.GCMParameterSpec;
import javax.crypto.spec.SecretKeySpec;

import lombok.extern.slf4j.Slf4j;

/**
 * 加密工具类
 */
@Slf4j
public class CryptUtils {
	
	private static final String MESSAGE_DIGEST_ALGORITHM  = "MD5";
	private CryptUtils() {}

	private static final String KEY_ALGORITHM = "AES";
	private static final String DEFAULT_CIPHER_ALGORITHM = "AES/GCM/NoPadding";// 默认的加密算法
	/**
	 * 加密
	 *
	 * @param src 数据源
	 * @param key 密钥
	 * @return 返回加密后的数据
	 * @throws Exception
	 */
	private static byte[] encrypt(byte[] src, byte[] key) {
		try {
			Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
			cipher.init(Cipher.ENCRYPT_MODE, generateSecretKey(key));
			byte[] iv = cipher.getIV();
			assert iv.length == 12;
			byte[] encryptData = cipher.doFinal(src);
			assert encryptData.length == src.length + 16;
			byte[] message = new byte[12 + src.length + 16];
			System.arraycopy(iv, 0, message, 0, 12);
			System.arraycopy(encryptData, 0, message, 12, encryptData.length);
			return message;
		} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException | IllegalBlockSizeException
				| BadPaddingException e) {
			log.error(e.getMessage(), e);
		}
		return new byte[0];
	}

	/**
	 * 解密
	 *
	 * @param src 数据源
	 * @param key 密钥
	 * @return 返回解密后的原始数据
	 * @throws Exception
	 */
	private static byte[] decrypt(byte[] src, byte[] key) {
		if (src.length < 12 + 16)
			throw new IllegalArgumentException();
		GCMParameterSpec params = new GCMParameterSpec(128, src, 0, 12);
		try {
			Cipher cipher = Cipher.getInstance(DEFAULT_CIPHER_ALGORITHM);
			cipher.init(Cipher.DECRYPT_MODE, generateSecretKey(key), params);
			return cipher.doFinal(src, 12, src.length - 12);
		} catch (InvalidKeyException | NoSuchAlgorithmException | NoSuchPaddingException
				| InvalidAlgorithmParameterException | IllegalBlockSizeException | BadPaddingException e) {
			log.error(e.getMessage(), e);
		}
		return new byte[0];
	}

	/**
	 * 数据解密
	 *
	 * @param data hex
	 * @param key  密钥
	 * @return String
	 * @throws Exception
	 */
	public static final String decrypt(String data, String key) {
		if (data != null) {
			return new String(decrypt(hex2byte(data.getBytes()), key.getBytes()));
		}
		return null;
	}

	/**
	 * 数据加密
	 *
	 * @param data
	 * @param key  密钥
	 * @return 加密结果 hex
	 * @throws Exception
	 */
	public static final String encrypt(String data, String key) {
		if (data != null && key !=null) {
				return byte2hex(encrypt(data.getBytes(), key.getBytes()));
		}
		return null;
	}

	/**
	 * 二行制转字符串
	 *
	 * @param b
	 * @return
	 */
	private static String byte2hex(byte[] b) {
		StringBuilder hs = new StringBuilder();
		String stmp;
		for (int n = 0; b != null && n < b.length; n++) {
			stmp = Integer.toHexString(b[n] & 0XFF);
			if (stmp.length() == 1) {
				hs.append('0');
			}
			hs.append(stmp);
		}
		return hs.toString().toUpperCase();
	}

	private static byte[] hex2byte(byte[] b) {
		if ((b.length % 2) != 0) {
			throw new IllegalArgumentException();
		}
		byte[] b2 = new byte[b.length / 2];
		for (int n = 0; n < b.length; n += 2) {
			String item = new String(b, n, 2);
			b2[n / 2] = (byte) Integer.parseInt(item, 16);
		}
		return b2;
	}

	/**
	 * 对字符串按密钥进行AES加密.
	 *
	 * @param data the data
	 * @return 加密结果 hex
	 */
	public static String encode(String data) {
		return encrypt(data, Constants.CRYPT_AES_KEY);
	}

	/**
	 * 对字符串按密钥进行AES解密.
	 *
	 * @param data hex
	 * @return 解密结果
	 */
	public static String decode(String data) {
		return decrypt(data, Constants.CRYPT_AES_KEY);
	}

	/**
	 * 对字符串按密钥进行AES加密.
	 *
	 * @param data the data
	 * @param key the key
	 * @return 加密结果base64
	 */
	public static String encode(String data, String key) {
		if (data != null && key != null) {
				return encryptBASE64(encrypt(data.getBytes(), key.getBytes()));
		}
		return null;
	}

	/**
	 * 对字符串按密钥进行AES解密.
	 *
	 * @param data base64
	 * @param key the key
	 * @return 解密结果
	 */
	public static String decode(String data, String key) {
		if (data == null || key == null) {
			return null;
		}
		return new String(decrypt(decryptBASE64(data), key.getBytes()));
	}

	// 根据密码和keyGenerator生成密钥。
	private static SecretKey generateSecretKey(byte[] key) throws NoSuchAlgorithmException {
		MessageDigest md = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM );
		md.update(key, 0, key.length);
		byte[] mdBytes = md.digest(); // Generate 16 bytes
		return  new SecretKeySpec(mdBytes, KEY_ALGORITHM);
	}

	/**
	 * 转换成字符串
	 */
	public static String convertToHexString(byte[] data) {
		StringBuilder strBuffer = new StringBuilder();
		for (int i = 0; i < data.length; i++) {
			String hex = Integer.toHexString(0xff & data[i]);
			if (hex.length() == 1) {
				hex = '0' + hex;
			}
			strBuffer.append(hex.toUpperCase());
		}
		return strBuffer.toString();
	}

	/**
	 * BASE64加密
	 */
	public static String encryptBASE64(byte[] key)  {
		return Base64.getEncoder().encodeToString(key);
	}

	/**
	 * BASE64解密
	 */
	public static byte[] decryptBASE64(String key)  {
		return Base64.getDecoder().decode(key);
	}

	public static String encodeBASE64(String str) {
		return  Base64.getEncoder().encodeToString(str.getBytes());
	}

	public static String encodeBASE64(byte[] bytes) {
		String encode = Base64.getEncoder().encodeToString(bytes);
		encode = encode.replace("\n", "");
		return encode;
	}

	/**
	 * 文件内容生成BASE64编码的字符串
	 */
	public static String encodeBASE64(File file) {
		StringBuilder sb = new StringBuilder();
		try(InputStream input = new FileInputStream(file);
				ByteArrayOutputStream out = new ByteArrayOutputStream()) {
			byte[] temp = new byte[1024];
			for (int len = input.read(temp); len != -1; len = input.read(temp)) {
				out.write(temp, 0, len);
				sb.append(Base64.getEncoder().encodeToString(out.toByteArray()));
				out.reset();
			}
		} catch (Exception e) {
			e.printStackTrace();
		}
		return sb.toString();
	}

	/**
	 * BASE64编码的字符串解码为文件
	 */
	public static void decodeBASE64(String encoder, File file) {
		try(FileOutputStream fos = new FileOutputStream(file)) {
			byte[] decoderBytes = Base64.getDecoder().decode(encoder);
			fos.write(decoderBytes);
			fos.flush();
		} catch (Exception e) {
			e.printStackTrace();
		}
	}

	public static byte[] decodeBASE64(String encoder) {
		return Base64.getDecoder().decode(encoder);
	}
	public static String getSign(String privateKey) {
		return getSign(privateKey, new Date());
	}
	public static String getMD5ofStr(String inStr) {
		MessageDigest md5 = null;
		try {
			// 获得MD5摘要算法的 MessageDigest 对象
			md5 = MessageDigest.getInstance(MESSAGE_DIGEST_ALGORITHM );
			byte[] byteArray = inStr.getBytes(StandardCharsets.UTF_8);
			// 获得密文
			byte[] md5Bytes = md5.digest(byteArray);
			// 把密文转换成十六进制的字符串形式
			StringBuilder hexValue = new StringBuilder();
			for (int i = 0; i < md5Bytes.length; i++) {
				int val = md5Bytes[i] & 0xff;
				if (val < 16) {
					hexValue.append("0");
				}
				hexValue.append(Integer.toHexString(val));
			}
			return hexValue.toString().toUpperCase();
		} catch (Exception e) {
			e.printStackTrace();
		}

		return "";
	}
	public static String getSign(String privateKey, Date date) {
		SimpleDateFormat sdf = new SimpleDateFormat("yyyyMMdd");
		return getMD5ofStr(privateKey + sdf.format(date));
	}
}
